package com.dailywork.basepro.lambda;

import java.util.stream.Stream;

public class Lambda6 {

    public static void main(String[] args) {
        String[] str = {"dx1", "dx2", "dx3", "dx4", "dx5"};
        String result =
                Stream.of(str)
                        .reduce(
                                new StringCombiner(",", "[", "]", str.length),
                                StringCombiner::add,
                                StringCombiner::merge)
                        .toString();
        System.out.println(result);
    }
}

class StringCombiner {

    private String prefix;

    private String suffix;

    private String delim;

    private int inputLen;

    private StringBuilder builder = new StringBuilder();

    StringCombiner(String delim, String prefix, String suffix, int inputLen) {
        this.delim = delim;
        this.prefix = prefix;
        this.suffix = suffix;
        this.inputLen = inputLen;
    }

    public StringCombiner add(String element) {
        if (builder.length() == 0) {
            builder.append(prefix);
        } else {
            builder.append(delim);
        }

        builder.append(element);

        inputLen = inputLen - 1;
        if (inputLen == 0) {
            builder.append(suffix);
        }
        return this;
    }

    public StringCombiner merge(StringCombiner other) {
        builder.append(other.builder);
        return this;
    }

    @Override
    public String toString() {
        return builder.toString();
    }
}
